package cn.gson.springboot.model.service;

import cn.gson.springboot.model.dao.StorageDao;
import cn.gson.springboot.model.dao.StorageDetailDao;
import cn.gson.springboot.model.mapper.StorageMapper;
import cn.gson.springboot.model.pojos.Storage;
import cn.gson.springboot.model.pojos.StorageDetail;
import cn.gson.springboot.model.vo.StorageDetailVo;
import cn.gson.springboot.model.vo.StorageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class StorageService {
    @Autowired
    StorageMapper stoMapper;
    @Autowired
    StorageDao stoDao;
    @Autowired
    StorageDetailDao stoDetailDao;;

    public List<Storage> selectStorage(Integer status, Integer warId,String stoTheme){
        return stoMapper.selectStorage(status,warId,stoTheme);
    }

    public Storage selectStorageById(Integer stoId){
        return stoMapper.selectStorageById(stoId);
    }

    public List<Storage> selectStorageByPurId(Integer purId){
        return stoMapper.selectStorageByPurId(purId);
    }

    @Transactional(transactionManager = "transactionManager")
    public Integer saveStorage(StorageVo vo){
        Storage s = new Storage();
        s.setStorageId(vo.getStorageId());
        s.setStorageTheme(vo.getStorageTheme());
        s.setStorageDate(vo.getStorageDate());
        s.setStorageStatus(vo.getStorageStatus());
        s.setStorageNote(vo.getStorageNote());
        s.setStorageExecutorDate(vo.getStorageExecutorDate());
        s.setWarehouseByWarehouseId(vo.getWarehouseByWarehouseId());
        s.setPurchaseByPurchaseId(vo.getPurchaseByPurchaseId());
        s.setCustomerByCustomerId(vo.getCustomerByCustomerId());
        s.setEmployeeByStoEmployeeId(vo.getEmployeeByStoEmployeeId());
        s.setEmployeeByAffEmployeeId(vo.getEmployeeByAffEmployeeId());
        s.setReturnByReturnId(vo.getReturnByReturnId());
        stoDao.save(s);
        List<StorageDetailVo> sdVo = vo.getStorageDetailsByStorageId();
        stoDetailDao.deleteByStoId(s.getStorageId());
        for (StorageDetailVo v:sdVo) {
            StorageDetail sd = new StorageDetail();
            sd.setStorageDetailId(v.getStorageDetailId());
            sd.setStorageDetailNum(v.getStorageDetailNum());
            sd.setStorageDetailNote(v.getStorageDetailNote());
            sd.setProductByProductId(v.getProductByProductId());
            sd.setStorageByStorageId(s);
            stoDetailDao.save(sd);
        }
        return s.getStorageId();
    }
    @Transactional(transactionManager = "transactionManager")
    public void deleteStorage( Integer stoId){
        stoDao.deleteById(stoId);
    }
}
